<template>
  <div class="page-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchForm.name"
        placeholder="请输入设施名称"
        style="width: 200px; margin-right: 10px"
      />
      <el-select
        v-model="searchForm.categoryId"
        placeholder="请选择设施分类"
        clearable
        style="width: 200px; margin-right: 10px"
      >
        <el-option
          v-for="item in allCategories"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-button type="primary" @click="loadData">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="primary" @click="handleAdd" style="margin-left: auto">
        添加设施
      </el-button>
    </div>

    <!-- 表格 -->
    <el-card class="table-card" shadow="never" :loading="loading">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="{
          background: '#f5f7fa',
          color: '#606266',
          fontWeight: 'bold',
          height: '50px',
        }"
        :cell-style="{
          padding: '12px 0',
        }"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column
          prop="name"
          label="设施名称"
          min-width="120"
          align="center"
        />
        <el-table-column
          prop="categoryId"
          label="设施分类"
          width="120"
          align="center"
        >
          <template #default="scope">
            <el-tag type="success">{{
              getCategoryName(scope.row.categoryId)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="设施地址"
          min-width="200"
          align="center"
        />
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="statusMap[scope.row.status as keyof typeof statusMap]">{{
              scope.row.status === 1 ? '正常' : scope.row.status === 2 ? '维修中' : '故障待修'
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加设施' : '编辑设施'"
      width="500px"
      @close="handleClose"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="设施名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="设施分类" prop="categoryId">
          <el-select
            v-model="form.categoryId"
            placeholder="请选择设施分类"
            style="width: 100%"
          >
            <el-option
              v-for="item in allCategories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设施地址" prop="address">
          <el-input v-model="form.address" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue"
import { ElMessage, ElMessageBox } from "element-plus"
import {
  pageRequest,
  addRequest,
  editRequest,
  delRequest,
  getAllCategoryRequest,
} from "../../../api/facility"

// 表格数据
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const allCategories = ref<any[]>([])

const statusMap = {
  1: "success",
  2: "warning",
  3: "danger",
}

// 搜索表单
const searchForm = reactive({
  name: "",
  categoryId: undefined as undefined | number,
})

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref("add")
const formRef = ref()
const form = reactive({
  id: "",
  name: "",
  categoryId: undefined as undefined | number,
  address: "",
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: "请输入设施名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  categoryId: [
    { required: true, message: "请选择设施分类", trigger: "change" },
  ],
  address: [
    { required: true, message: "请输入设施地址", trigger: "blur" },
    { min: 5, max: 200, message: "长度在 5 到 200 个字符", trigger: "blur" },
  ],
}

// 获取所有设施分类
const getAllCategories = async () => {
  try {
    const res: any = await getAllCategoryRequest()
    if (res.code === 200) {
      allCategories.value = res.data.records
    }
  } catch (error) {
    console.error("获取设施分类失败:", error)
    ElMessage.error("获取设施分类失败")
  }
}

// 获取分类名称
const getCategoryName = (categoryId: number) => {
  const category = allCategories.value.find(
    (item: any) => item.id === categoryId
  )
  return category ? category.name : "-"
}

// 加载表格数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      ...searchForm,
    }
    const res: any = await pageRequest(params)
    if (res.code === 200) {
      tableData.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    console.error("加载数据失败:", error)
    ElMessage.error("加载数据失败")
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ""
  searchForm.categoryId = undefined
  currentPage.value = 1
  loadData()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadData()
}

// 清空表单
const resetForm = () => {
  form.id = ""
  form.name = ""
  form.categoryId = undefined
  form.address = ""
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 添加设施
const handleAdd = () => {
  dialogType.value = "add"
  dialogVisible.value = true
  resetForm()
}

// 编辑设施
const handleEdit = (row: any) => {
  dialogType.value = "edit"
  dialogVisible.value = true
  resetForm()
  Object.assign(form, row)
}

// 删除设施
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确认删除该设施吗？删除后不可恢复！", "提示", {
    type: "warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(async () => {
      try {
        await delRequest(row.id)
        ElMessage.success("删除成功")
        loadData()
      } catch (error:any) {
        console.error("删除失败:", error)
        ElMessage.error(error.response?.data?.msg || "删除失败")
      }
    })
    .catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        if (dialogType.value === "add") {
          await addRequest(form)
          ElMessage.success("添加成功")
        } else {
          await editRequest(form)
          ElMessage.success("编辑成功")
        }
        dialogVisible.value = false
        loadData()
      } catch (error: any) {
        console.error("操作失败:", error)
        ElMessage.error(error.response?.data?.msg || "操作失败")
      } finally {
        loading.value = false
      }
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  getAllCategories()
  loadData()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  height: 100%;
  background-color: #f5f7fa;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  padding: 20px;
  display: flex;
  justify-content: flex-end;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

:deep(.el-card__body) {
  padding: 0;
}

:deep(.el-table) {
  border-radius: 4px;
}
</style>
